package com.pw.study.flink.chapter9;

import com.pw.study.flink.entities.OrderEvent;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternFlatSelectFunction;
import org.apache.flink.cep.PatternFlatTimeoutFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.CoProcessFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.List;
import java.util.Map;

public class MyCepOrder3 {
    public static void main(String[] args) {
        login();
    }

    private static void login() {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);

        //输入数据
        SingleOutputStreamOperator<OrderEvent> data = env.readTextFile("data/file/OrderLog.csv").map(ads -> {
            String[] line = ads.split(",");
            return new OrderEvent(Long.valueOf(line[0]), line[1], line[2], Long.valueOf(line[3]) * 1000);
        });
        WatermarkStrategy<OrderEvent> strategy = WatermarkStrategy.<OrderEvent>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                .withTimestampAssigner(new SerializableTimestampAssigner<OrderEvent>() {
                    @Override
                    public long extractTimestamp(OrderEvent order, long ts) {
                        return order.getEventTime();
                    }
                });
        KeyedStream<OrderEvent, Long> stream = data.assignTimestampsAndWatermarks(strategy).keyBy(OrderEvent::getOrderId);

        Pattern<OrderEvent, OrderEvent> pattern = Pattern.<OrderEvent>begin("create").where(new SimpleCondition<OrderEvent>() {
                    @Override
                    public boolean filter(OrderEvent orderEvent) throws Exception {
                        return orderEvent.getEventType().equals("create");
                    }
                }).optional()
                .next("pay").where(new SimpleCondition<OrderEvent>() {
                    @Override
                    public boolean filter(OrderEvent orderEvent) throws Exception {
                        return orderEvent.getEventType().equals("pay");
                    }
                }).within(Time.minutes(15));

        PatternStream<OrderEvent> ps = CEP.pattern(stream, pattern);

        OutputTag<OrderEvent> outputTag = new OutputTag<OrderEvent>("timeout") {
        };

        SingleOutputStreamOperator<OrderEvent> result = ps.flatSelect(outputTag, new PatternFlatTimeoutFunction<OrderEvent, OrderEvent>() {
            @Override
            public void timeout(Map<String, List<OrderEvent>> map, long ts, Collector<OrderEvent> out) throws Exception {
                OrderEvent create = map.get("create").get(0);
                String msg = "订单：" + create.getOrderId() + " 没有订单支付，或者支付超时。。。。。。";
                out.collect(create);
            }
        }, new PatternFlatSelectFunction<OrderEvent, OrderEvent>() {
            @Override
            public void flatSelect(Map<String, List<OrderEvent>> map, Collector<OrderEvent> out) throws Exception {
                if (!map.containsKey("create")) {
                    OrderEvent pay = map.get("pay").get(0);
                    String msg = "订单:" + pay.getOrderId() + " 只有pay没有create, 请检查系统bug";
                    System.out.println(msg);
                    out.collect(pay);
                }
            }
        });
        DataStream<OrderEvent> sideOutput = result.getSideOutput(outputTag);
        result.connect(sideOutput).keyBy(OrderEvent::getOrderId, OrderEvent::getOrderId)
                .process(new CoProcessFunction<OrderEvent, OrderEvent, String>() {
                    private ValueState<OrderEvent> createState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        createState = getRuntimeContext().getState(new ValueStateDescriptor<OrderEvent>("createState", OrderEvent.class));
                    }

                    @Override
                    public void processElement1(OrderEvent value, Context ctx, Collector<String> out) throws Exception {
                        if (createState.value() == null) {
                            out.collect(value.getOrderId() + " 只有pay，没有create。。。。");
                        } else {
                            out.collect(value.getOrderId() + " pay超时支付。。。。。。");
                        }
                    }

                    @Override
                    public void processElement2(OrderEvent value, Context ctx, Collector<String> out) throws Exception {
                        System.out.println("processElement2..................");
                        createState.update(value);
                    }
                }).print();


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
